package fpt.edu.vn.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import fpt.edu.vn.dao.AddnewDao;
import fpt.edu.vn.dao.TopicsDao;
import fpt.edu.vn.model.Activityhistorys;
import fpt.edu.vn.model.Topicimages;
import fpt.edu.vn.model.Topics;
import fpt.edu.vn.model.Users;
import fpt.edu.vn.util.ImageUtil;
import fpt.edu.vn.util.SolrQuerying;

/* 
 * DetailAction.java 
 *  
 * 0.1
 * 
 * 10/15/2012 
 *  
 * Copyright notice 
 *  
 * Modification Logs: 
 *   DATE        AUTHOR      DESCRIPTION 
 *  -------------------------------------------------------- 
 *  15-Oct-2012  ThuongND    Create new 
 */
public class AddTopicAction extends ActionSupport implements
		ServletRequestAware {

	private static final long serialVersionUID = 1L;
	private String email;
	private List<Users> userList;
	private Users user = new Users();
	private Topics topic = new Topics();
	private String title;
	private String address;
	private int district;
	private String Username;
	private int topicId;
	private int districtId;
	private float price;
	private float area;
	private String contact;
	private String phone;
	private String description;
	private String latitude;
	private String longitude;
	private int topicTypeId;
	private int viewNum;
	private int owner;
	private int toilet;
	private int internet;
	private int houseType;
	private int motor;
	private String image;
	private String water;
	private String power;
	private String hour;
	private String motorPrice = null;
	private int cook;
	

	private HttpServletRequest servletRequest;
	private int UserId;
	private File imageTopic[];
	private String imageTopicContentType;
	private String imageTopicFileName;
	private String urlImg;
	private ImageUtil imgutil = new ImageUtil();
	private SolrQuerying solQ = new SolrQuerying();
	private AddnewDao addnewdao = new AddnewDao();
	// For SessionAware
	Map<String, Object> session;

	private Activityhistorys activityhistory = new Activityhistorys();
	private TopicsDao dao = new TopicsDao();

	public String execute() {

		String ipaddress = "";
		session = ActionContext.getContext().getSession();
		if (session.containsKey("ipaddress")) {
			ipaddress = (String) session.get("ipaddress");
		}
		boolean blnoimg = false;
		session = ActionContext.getContext().getSession();
		email = (String) session.get("emailss");
		String displayNamess = "";
		StringBuilder stbpathImgTopic = new StringBuilder();
		int userId_ = 0;
		session = ActionContext.getContext().getSession();
		if (session.containsKey("userIdss")) {
			userId_ = (Integer) session.get("userIdss");
			setUserId(userId_);
		}

		displayNamess = (String) session.get("displayNamess");
		if (email != null) {
			if ("".equals(displayNamess) || displayNamess == null) {
				setUsername(null);
			} else {
				setUsername(displayNamess);
			}
			// upload image to dir
			try {
				String filePath = servletRequest.getRealPath("/Img/Topic/");
				if (imageTopic != null) {

					String temp[] = imageTopicFileName.split(",");
					int i = 0;
					for (String imgh : temp) {
						StringBuilder stbnameImg = new StringBuilder();
						stbnameImg.append(getStrDate());
						stbnameImg.append("-");
						stbnameImg.append(userId_);
						stbnameImg.append("-");
						stbnameImg.append(imgh);
						String pathname = stbnameImg.toString()
								.replace(" ", "").replace(":", "")
								.replace(",", "");

						File fileToCreate = new File(filePath, pathname);
						FileUtils.copyFile(this.imageTopic[i], fileToCreate);
						if (i == 0) {
							// add 1 image to topic table
							
							urlImg= imgutil.leechIMG(this.imageTopic[i]);
							setImage(pathname);
							stbpathImgTopic.append(pathname);
						} else {
							stbpathImgTopic.append("," + pathname);
						}
						// add to topicImage

						i++;
					}
				} else {
					setImage("icon-chothue.png");
					blnoimg = true;
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// get userID
			topic.setUsersId(userId_);
			topic.setTitle(title);
			// topic post = 1 or share =2
			topic.setTopicTypeId(1);
			topic.setStatusTopicId(1);
			topic.setCreateDate(getSysdate());
			topic.setRenewDate(getSysdate());
			topic.setEditDate(getSysdate());
			topic.setDistrictId(district);
			topic.setAddress(address);
			topic.setPrice(price);
			topic.setArea(area);
			topic.setContact(contact);
			topic.setPhone(phone);
			topic.setDescription(description);
			// set Latitude
			topic.setLatitude(latitude);
			// set Longitude
			topic.setLongitude(longitude);
			// view num set =0
			viewNum = 0;
			topic.setViewNum(viewNum);
			topic.setImage(image);
			topic.setOwner(owner);
			topic.setWater(water);
			topic.setPower(power);
			topic.setToilet(toilet);
			topic.setInternet(internet);
			topic.setHouseType(houseType);
			topic.setHour(hour);
			topic.setMotor(motor);
			if(!"nghìn đồng/th".equals(motorPrice))
			topic.setMotorPrice(motorPrice);
			topic.setCook(cook);
			if (title == null || address == null || description == null) {
				return ERROR;
			}
			// check topic exist
			List<Topics> tpExist = addnewdao.topicexist(userId_, title,
					address, description);

			if (tpExist.size() > 0) {
				return ERROR;
			} else {
				topic = addnewdao.add(topic);
				topicId = topic.getTopicId();
				districtId = topic.getDistrictId();
				String title_ = topic.getTitle();

				// Insert vao history
				activityhistory.setActivityTypeId(4);
				activityhistory.setIpAddress(ipaddress);
				activityhistory.setUserName(email);
				activityhistory.setTopicId(topicId);
				activityhistory.setTitle(title_);
				activityhistory.setDistrictId(districtId);
				dao.add(activityhistory);

				if (!blnoimg && topicId != 0) {
					String temp[] = stbpathImgTopic.toString().split(",");
					for (String path : temp) {
						Topicimages topicimages = new Topicimages();
						topicimages.setTopicId(topicId);
						topicimages.setPath(path);
						addnewdao.add(topicimages);
					}
				}
				// addnewdao.topicfb((Integer)session.get("userIdss"));
				try {
					solQ.updateDataFromMysqlToSolr();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return SUCCESS;
			}

		} else {
			return ERROR;
		}

	}

	public Date getSysdate() {
		Date date = new Date();
		return date;
	}

	public String getStrDate() {
		String curdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(Calendar.getInstance().getTime());
		return curdate;
	}

	public String getUsername() {
		return Username;
	}

	public void setUsername(String username) {
		Username = username;
	}
	
	public String getUrlImg() {
		return urlImg;
	}

	public void setUrlImg(String urlImg) {
		this.urlImg = urlImg;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Users getUser() {
		return user;
	}

	public void setUser(Users user) {
		this.user = user;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	public float getArea() {
		return area;
	}

	public void setArea(float area) {
		this.area = area;
	}

	public String getContact() {
		return contact;
	}

	public void setContact(String contact) {
		this.contact = contact;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getLatitude() {
		return latitude;
	}

	public void setLatitude(String latitude) {
		this.latitude = latitude;
	}

	public String getLongitude() {
		return longitude;
	}

	public void setLongitude(String longitude) {
		this.longitude = longitude;
	}

	public int getTopicTypeId() {
		return topicTypeId;
	}

	public void setTopicTypeId(int topicTypeId) {
		this.topicTypeId = topicTypeId;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getViewNum() {
		return viewNum;
	}

	public void setViewNum(int viewNum) {
		this.viewNum = viewNum;
	}

	public int getOwner() {
		return owner;
	}

	public void setOwner(int owner) {
		this.owner = owner;
	}

	public int getToilet() {
		return toilet;
	}

	public void setToilet(int toilet) {
		this.toilet = toilet;
	}

	public int getInternet() {
		return internet;
	}

	public void setInternet(int internet) {
		this.internet = internet;
	}

	public int getHouseType() {
		return houseType;
	}

	public void setHouseType(int houseType) {
		this.houseType = houseType;
	}

	public int getMotor() {
		return motor;
	}

	public void setMotor(int motor) {
		this.motor = motor;
	}

	public String getImage() {
		return image;
	}

	public void setImage(String image) {
		this.image = image;
	}

	public String getWater() {
		return water;
	}

	public void setWater(String water) {
		this.water = water;
	}

	public String getPower() {
		return power;
	}

	public void setPower(String power) {
		this.power = power;
	}

	public String getHour() {
		return hour;
	}

	public void setHour(String hour) {
		this.hour = hour;
	}

	public String getMotorPrice() {
		return motorPrice;
	}

	public void setMotorPrice(String motorPrice) {
		this.motorPrice = motorPrice;
	}

	public int getDistrict() {
		return district;
	}

	public void setDistrict(int district) {
		this.district = district;
	}

	public int getTopicId() {
		return topicId;
	}

	public void setTopicId(int topicId) {
		this.topicId = topicId;
	}

	public int getDistrictId() {
		return districtId;
	}

	public void setDistrictId(int districtId) {
		this.districtId = districtId;
	}

	public File[] getImageTopic() {
		return imageTopic;
	}

	public void setImageTopic(File[] imageTopic) {
		this.imageTopic = imageTopic;
	}

	public String getImageTopicContentType() {
		return imageTopicContentType;
	}

	public void setImageTopicContentType(String imageTopicContentType) {
		this.imageTopicContentType = imageTopicContentType;
	}

	public String getImageTopicFileName() {
		return imageTopicFileName;
	}

	public void setImageTopicFileName(String imageTopicFileName) {
		this.imageTopicFileName = imageTopicFileName;
	}

	public int getUserId() {
		return UserId;
	}

	public void setUserId(int userId) {
		UserId = userId;
	}

	@Override
	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;

	}

	public int getCook() {
		return cook;
	}

	public void setCook(int cook) {
		this.cook = cook;
	}

	public Activityhistorys getActivityhistory() {
		return activityhistory;
	}

	public void setActivityhistory(Activityhistorys activityhistory) {
		this.activityhistory = activityhistory;
	}

}
